#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"
void HPinit(HP* php) {
	assert(php);
	php->data = NULL;
	php->capacity = php->size = 0;
}
void destory(HP* php) {
	assert(php);
	free(php);
	php->data = NULL;
	php->capacity = php->size = 0;
}

void swap(HPDataType* child, HPDataType* parent) {
	HPDataType tmp = *child;
	*child = *parent;
	*parent = tmp;

}
void AdjustUp(HPDataType* data, int child) {
	int parent = (child - 1) / 2;
	while (child) {
		if (data[parent] > data[child]) {
			swap(&data[parent], &data[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
			{
				break;
			}
			
	}
};
void HPpush(HP* php, HPDataType x) {
	assert(php);
	if (php->capacity == php->size) {
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(php->data, newcapacity * sizeof(HPDataType));
		if (tmp == NULL) {
			perror("malloc error");
			return;
		}
		php->capacity = newcapacity;
		php->data = tmp;
	}
	php->data[php->size] = x;
	php->size++;
	AdjustUp(php->data, php->size - 1);

}


void AdjustDown(HPDataType* a,int n,int parent) {
	int child = parent * 2 + 1;
	
	while (child < n) {
		if (child+1<n&&a[child] > a[child + 1]) {
			child += 1;
		}
		if ( a[child] < a[parent]) {
			swap(&a[parent], &a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else {
			break;
		}
	}
}
void HPPop(HP* php) {
	assert(php);
	assert(php->size);
	swap(&php->data[0], &php->data[php->size - 1]);
	php->size--;
	AdjustDown(php->data, php->size, 0);
}
int HPTop(HP* php) {
	assert(php);
	assert(php->size);
	return php->data[0];
}
bool HPempty(HP* php) {
	assert(php);
	return php->size==0;
}